import os.path
import subprocess

from config.sys_path import ITEM_DIR


def upgrade_pip():
    # 获取所有可更新的包
    packages = subprocess.check_output(['pip', 'list', '--outdated']).decode('utf-8').split('\n')[2:-1]
    # 需要排除的包名列表
    exclude_list = ['xlrd', 'pyee']
    # 过滤掉需要排除的包
    packages = [pkg.split()[0] for pkg in packages if pkg.split()[0] not in exclude_list]
    if packages:
        # 升级所有包
        subprocess.call(['pip', 'install', '--upgrade'] + packages)
        # 如果更新升级了playwright，则需要重新安装专属浏览器
        if 'playwright' in packages:
            subprocess.call(['playwright', 'install'], shell=True)
        # 更新requirements.txt文件
        txt_path = os.path.join(ITEM_DIR, 'requirements.txt')
        subprocess.call(['pip', 'freeze', '>', txt_path], shell=True)
    else:
        print('没有需要更新的模块')


if __name__ == '__main__':
    upgrade_pip()
